import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';
import { observer } from 'mobx-react';

import ContentLayout from '@/component/common/ContentLayout';
import MTable from '@/component/common/MTable';
import { Pagination, Form, Input, Select, Upload, Icon, message, Spin } from 'antd';
import MModal from '@/component/common/MModal';
import helper from '@/tool/helper';

import format from '@/tool/format';

const mConfirm = MModal.confirm;
const FormItem = Form.Item;
const Option = Select.Option;

import style from './houseList.scss';

import FilterListPage from '@/component/common/FilterListPage';

import ApiHelper from '@/store/ApiHelper';
import { house_list as api_house_list, pull_house_into_Recycle_bin, house_verify_apply,
    upload_picture } from '@/constants/ApiTypes';
import StoreListMini from '@/store/StoreListMini';
import BrokerListMini from '@/store/BrokerListMini';
import HeaderNavStore from '@/store/HeaderNav';
import adminType from '@/tool/adminType';
import { SITE_URL, API_URL } from '@/config';
import HouseEditModal from '@/component/house/HouseEditModal';

@observer class Filter extends Component {
    static propTypes = {
        form: PropTypes.any,
        onSubmit: PropTypes.func
    };
    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (this.props.onSubmit) {
                    for (let key in values) {
                        if (values[key] === '') delete values[key];
                    }
                    this.props.onSubmit(values);
                }
            }
        });
    };
    selectStore = value => {
        this.props.form.setFieldsValue({ broker_name: '' });
        if (value == '') {
            return BrokerListMini.info.clear();
        }
        BrokerListMini.getInfo(value);
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        const storeListMini = StoreListMini.info;
        const brokerListMini = BrokerListMini.info;

        let storeOptionList = storeListMini.map((val, index) => {
            return <Option key={index} value={`${val.store_id}`}>{val.store_name}</Option>;
        });
        let brokerOptionList = brokerListMini.map((val, index) => {
            return <Option key={index} value={`${val.realname}`}>{val.realname}</Option>;
        });
        return (
            <Form layout="inline" onSubmit={this.handleSubmit}>
                {adminType() == 1 &&
                <FormItem label="门店">
                    {getFieldDecorator('store_id', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择门店" style={{ width: 150 }} onChange={this.selectStore}>
                            <Option key="default" value="">不限</Option>
                            {storeOptionList}
                        </Select>
                    )}
                </FormItem>}
                <FormItem label="经纪人">
                    {getFieldDecorator('broker_name', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择经纪人" style={{ width: 150 }}>
                            <Option key="default" value="">不限</Option>
                            {brokerOptionList}
                        </Select>
                    )}
                </FormItem>
                <FormItem label="城区">
                    {getFieldDecorator('area', {
                        initialValue: ''
                    })(
                        <Input/>
                    )}
                </FormItem>
                <FormItem label="房源编号">
                    {getFieldDecorator('house_no', {
                        initialValue: ''
                    })(
                        <Input/>
                    )}
                </FormItem>
                <FormItem>
                    <button className={style['submit-btn']} type="submit">搜索</button>
                </FormItem>
            </Form>
        );
    }
}
const FilterWrapped = Form.create()(Filter);

class AuthenticationModal extends Component {
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        owner_uid: PropTypes.any.isRequired,
        house_no: PropTypes.string.isRequired,
        community: PropTypes.string.isRequired
    };
    defaultState = {
        previewVisible: false,
        previewImage: '',
        ownerFileList: [],
        ownerImages: '',
        brokerFileList: [],
        brokerImages: '',
        address: '',
        houseProperty: '',
        spinning: false
    };

    state = this.defaultState;

    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
        }
    }
    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true
        });
    };
    ownerHandleChange = ({ fileList }) => {
        this.handleFileUpload(fileList);
        this.setState({
            ownerFileList: fileList,
            ownerImages: this.fileChange(fileList)
        });
    };
    handleFileUpload = fileList => {
        fileList.forEach((val, index) => {
            if (val.status == 'done' && val.response && !val.response.status) {
                fileList[index].status = 'error';
                MModal.success({ title: '上传失败', content: val.response.info, duration: 1.5 })
            }
        });
        return fileList;
    };
    brokerHandleChange = ({ fileList }) => {
        this.handleFileUpload(fileList);
        this.setState({
            brokerFileList: fileList,
            brokerImages: this.fileChange(fileList)
        });
    };
    //返回生成上传成功图片id数组
    fileChange = fileList => {
        let newFileList = [];
        fileList.forEach(val => {
            if (val.response && val.response.status) {
                newFileList.push(val.response.info[0].id);
            }
        });
        return newFileList.join(',');
    };
    inputChange = e => {
        let name = e.target.name;
        let value = e.target.value;
        this.setState({
            [name]: value
        });

    };
    submitApply = async () => {
        const { onClose, owner_uid, house_no, community } = this.props;
        const { address, houseProperty, ownerImages, brokerImages } = this.state;
        if (format.trim(address) == '') {
            this.input_address.refs.input.select();
            return message.warn('请输入详细地址！', 1.5);
        }
        if (format.trim(houseProperty) == '') {
            this.input_houseProperty.refs.input.select();
            return message.warn('请输入产权证号！', 1.5);
        }
        if (ownerImages == '') {
            return message.warn('请上传房东资料！', 1.5);
        }
        if (brokerImages == '') {
            return message.warn('请上传委托资料！', 1.5);
        }
        this.setState({ spinning: true });

        const data = {
            owner_uid, house_no, property: houseProperty, address: community + address,
            property_imgs: ownerImages, agent_imgs: brokerImages
        };

        const result = await ApiHelper.requestPost(house_verify_apply, data);
        this.setState({ spinning: false });
        if (result.status) {
            MModal.success({ title: '操作成功', content: '已申请认证，等待后台处理' });
            onClose();
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    render() {
        const { visible, onClose, community, house_no, owner_uid } = this.props;
        const { previewVisible, previewImage, ownerFileList, brokerFileList,
            address, houseProperty } = this.state;
        const { ownerHandleChange, brokerHandleChange, handlePreview, submitApply, inputChange } = this;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">上传图片</div>
            </div>
        );
        return (
            <MModal visible={visible} onClose={onClose} showMask closeMaskOnClick={false} width={625} height={helper.fixHeight(570)}>
                <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                    <div className={style['house-authentication-modal']}>
                        <div className={style['label-item']}>
                            <span className={style['label-text']}>{community}</span>
                            <Input ref={input => this.input_address = input} name="address" value={address} onChange={inputChange} />
                        </div>
                        <div className={style['label-item']}>
                            <span className={style['label-text']}>产权证号</span>
                            <Input ref={input => this.input_houseProperty = input} name="houseProperty" value={houseProperty} onChange={inputChange} />
                        </div>
                        <div className={style['label-item']}>
                            <span className={style['label-text']}>房东资料</span>
                            <div className={style['upload-wrap']}>
                                <Upload
                                    action={`${API_URL}/${upload_picture}`}
                                    listType="picture-card"
                                    fileList={ownerFileList}
                                    onPreview={handlePreview}
                                    onChange={ownerHandleChange}
                                    multiple
                                    accept=".jpg, .png"
                                    name="image"
                                    data={{ type: 'property', house_no, uid: owner_uid }}
                                >
                                    {uploadButton}
                                </Upload>
                            </div>
                        </div>
                        <div className={style['label-item']}>
                            <span className={style['label-text']}>委托资料</span>
                            <div className={style['upload-wrap']}>
                                <Upload
                                    action={`${API_URL}/${upload_picture}`}
                                    listType="picture-card"
                                    fileList={brokerFileList}
                                    onPreview={handlePreview}
                                    onChange={brokerHandleChange}
                                    multiple
                                    accept=".jpg, .png"
                                    name="image"
                                    data={{ type: 'agent', house_no, uid: owner_uid }}
                                >
                                    {uploadButton}
                                </Upload>
                            </div>
                        </div>
                        <MModal visible={previewVisible} onClose={this.handleCancel} showMask width={520} height={520} zIndex={101}>
                            <div className="image-preview-modal">
                                <img alt="图片预览" src={previewImage} />
                            </div>
                        </MModal>
                        <div className={style['modal-oper']}>
                            <a className={style['submit-btn']} href="javascript:void(0);" onClick={submitApply}>提交认证</a>
                        </div>
                    </div>
                </Spin>
            </MModal>
        );
    }
}

@observer class HouseList extends FilterListPage {
    constructor(props) {
        super(props);
        const state = {
            authenticationVisible: false,
            houseEditModalVisible: false,
            houseEditModalProps: {
                itemInfo: {
                    house_no: '',
                    broker_id: ''
                }
            },
            authenticationModalProps: {
                owner_uid: '',
                house_no: '',
                community: ''
            }
        };
        this._setDefaultState(state);
        this.listApiType = api_house_list;
    }
    pageBeforeMount() {
        HeaderNavStore.addHouseListNav();
    }
    async pageDidMount() {
        const result = await StoreListMini.getInfo();
        if (!result) return;
        this._setState({ loading: false });
    }
    componentWillUnmount() {
        HeaderNavStore.removeAllExtra();
    }
    showAuthenticationModal = (owner_uid, house_no, community) => {
        this.setState({
            authenticationVisible: true,
            authenticationModalProps: {
                owner_uid,
                house_no,
                community
            }
        });
    };
    closeAuthenticationModal = () => {
        this.setState({ authenticationVisible: false });
    };
    deleteHouseConfirm = house_no => {
        mConfirm({
            title: '是否将该房源放入回收站',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { house_no };
                const result = await ApiHelper.requestPost(pull_house_into_Recycle_bin, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
                    //刷新房源模式列表 //关闭当前模态框
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() { }
        });
    };
    closeHouseEditModal = refresh => {
        this.setState({ houseEditModalVisible: false });
        if (refresh === true) this.refresh();
    };
    showHouseEditModal = (house_no, broker_id) => {
        this.setState({
            houseEditModalVisible: true,
            houseEditModalProps: {
                itemInfo: {
                    house_no, broker_id
                }
            }
        });
    };
    render() {
        const { authenticationVisible, dataList, spinning, houseEditModalVisible, houseEditModalProps,
            authenticationModalProps } = this.state;
        const { pageOnChange, showAuthenticationModal, closeAuthenticationModal,
            deleteHouseConfirm, showHouseEditModal, closeHouseEditModal } = this;
        const verify_oper = (text, record, dataIndex) => {
            return parseInt(text) ? '已认证' : <a href="javascript:void(0);" onClick={() =>
                showAuthenticationModal(record.broker_id, record.house_no, record.community)}>去认证</a>
        };
        const house_star = (text, record, dataIndex) => {
            let star = text;
            if (star < 0) star = 0;
            if (star > 5) star = 5;
            let house_quality = '';
            if (star >= 0 && star < 3) {
                house_quality = '低';
            }
            if (star >= 3 && star < 4) {
                house_quality = '良'
            }
            if (star >= 4 && star <= 5) {
                house_quality = '优'
            }
            let stars = Array(5).fill('☆').map(val => {
                if (star > 0) val = '★';
                star--;
                return val;
            });
            return <div>{house_quality}<span className={style['house-stars']}>{stars}</span></div>;

        };

        const house_oper = (text, record, dataIndex) => {
            return (
                <div>
                    <a href={`${SITE_URL}/house_detail/${record.house_no}`} target="_blank">预览</a>/
                    <a href="javascript:void(0);" onClick={() => showHouseEditModal(record.house_no, record.broker_id)}>编辑</a>/
                    <a href="javascript:void(0);" onClick={() => deleteHouseConfirm(record.house_no)}>删除</a>
                </div>
            );
        };
        const columns = [
            { title: '房源编号', dataIndex: 'house_no', align: 'middle' },
            { title: '租赁方式', dataIndex: 'rent_type', align: 'middle' },
            { title: '城区', dataIndex: 'area', align: 'middle' },
            { title: '物业地址', dataIndex: 'community', align: 'middle' },
            { title: '面积', dataIndex: 'house_area', align: 'middle', render: (text, record, dataIndex) =>  `${text}㎡` },
            { title: '租金', dataIndex: 'rent', align: 'middle', render: (text, record, dataIndex) =>  `${text / 100}元` },
            { title: '经纪人', dataIndex: 'broker_name', align: 'middle' },
            { title: '所属门店', dataIndex: 'store_name', align: 'middle' },
            { title: '操作', dataIndex: 'i', align: 'middle', render: house_oper },
            { title: '认证', dataIndex: 'verify', align: 'middle', render: verify_oper },
            { title: '房源质量', dataIndex: 'star', align: 'middle', render: house_star }
        ];
        return (
            <ContentLayout navTitle="房源列表" loading={this.state.loading}>
                <div className={style['top-wrap']}>
                    <div className={style['house-mode-nav']}>
                        <NavLink exact to="/房源" activeClassName={style['active']}>房源模式</NavLink>
                        <NavLink exact to="/房源/房源列表" activeClassName={style['active']}>房源列表</NavLink>
                    </div>
                    <div className={style['top-filter']}>
                        <FilterWrapped onSubmit={this.getDataListWithFilter} />
                    </div>
                    <MTable columns={columns} dataSource={dataList} spinning={spinning}/>
                    <div className="pagination">
                        {this.state.total > 0 && <Pagination showQuickJumper current={this.state.current_page} pageSize={10} total={this.state.total} onChange={pageOnChange} />}
                    </div>
                    <AuthenticationModal visible={authenticationVisible} {...authenticationModalProps} onClose={closeAuthenticationModal} />
                    <HouseEditModal visible={houseEditModalVisible} {...houseEditModalProps} onClose={closeHouseEditModal} />
                </div>
            </ContentLayout>
        );
    }
}

export default HouseList;